//
// Copyright (c) 2010 Luís Reis
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using Pine.Core;

namespace Pine.IO
{
	public class Console : ClassInstance
	{
		public static readonly PineType ConsoleType = new DynamicType(null, null, null, null);
		public static readonly Console ConsoleValue = new Console();
		
		private Console() {
			ReadLineWrapper = new Function(null, delegate(Function f, ValueList vl) {
				vl.Clear();
				vl.SetArrayElement(new Number(0), ReadLine());
			});
			
			WriteWrapper = new Function(null, delegate(Function f, ValueList vl) {
				Value v = vl.GetArrayElement(0);
				vl.Clear();
				Write(v);
			});
			
			WriteLineWrapper = new Function(null, delegate(Function f, ValueList vl) {
				Value v = vl.GetArrayElement(0);
				vl.Clear();
				WriteLine(v);
			});
		}
		
		private Value ReadLine() {
			return new StringValue(System.Console.ReadLine());
		}
		
		private Function ReadLineWrapper;
		
		private void Write(Value val) {
			System.Console.Write(val.ToString());	
		}
		
		private Function WriteWrapper;
		
		private void WriteLine(Value val) {
			if (val.GetPineType() == NullValue.Null)
				System.Console.WriteLine();
			else
				System.Console.WriteLine(val.ToString());
		}
		
		private Function WriteLineWrapper;
		
		public override Value GetPineType() {
			return ConsoleType;
		}
		
		public override Value FieldGet (string fieldname)
		{
			if (fieldname == "readline")
				return ReadLineWrapper;
			if (fieldname == "write")
				return WriteWrapper;
			if (fieldname == "writeline")
				return WriteLineWrapper;
			return base.FieldGet (fieldname);
		}
	}
}

